package com.yning.coroutines.demo

import kotlinx.coroutines.*
import kotlin.concurrent.thread
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
import kotlin.coroutines.intrinsics.*

class Token
class Image
class Item
suspend fun requestToken() : Token {return Token()
} // suspend 挂起函数
suspend fun requestImage(token: Token, item: Item) : Image {return Image()
} // suspend 挂起函数
fun load(iamge : Image){} // 普通函数

fun loadRemoteImage(item: Item){
    // 协程运行
    GlobalScope.launch {
        val token = requestToken()
        val image = requestImage(token, item)
        load(image)
    }

}

/*@ObsoleteCoroutinesApi
fun main(args: Array<String>) {
    // 创建一个单线程的协程调度器，下面两个协程都运行在这同一线程上
    val coroutineDispatcher = newSingleThreadContext("ctx")
    // 启动协程 1
    GlobalScope.launch(coroutineDispatcher) {
        println("the first coroutine")
        delay(200)
        println("the first coroutine")
    }
    // 启动协程 2
    GlobalScope.launch(coroutineDispatcher) {
        println("the second coroutine")
        delay(100)
        println("the second coroutine")
    }
    // 保证 main 线程存活，确保上面两个协程运行完成
    Thread.sleep(500)
}*/

fun log(string: String){
    println("[${Thread.currentThread().name}]  ${string}")
}

suspend fun main() {
    val exceptionHandler = CoroutineExceptionHandler { coroutineContext, throwable ->
        log("${coroutineContext[CoroutineName]} $throwable")
    }
    val seq = sequence{
        yield(1)
    }
    GlobalScope.launch(exceptionHandler) {
        throw ArithmeticException("Hey!")
    }.join()
}

class User
typealias Callback = (User) -> Unit

fun getUser(callback: Callback){

}

suspend fun hello() = suspendCoroutineUninterceptedOrReturn<Int>{
    continuation ->
    log("1")
    thread {
        Thread.sleep(1000)
        log("2")
        continuation.resume(1024)
    }
    log("3")
    COROUTINE_SUSPENDED
}

suspend fun demoSupendFun(): String {
    return suspendCoroutine {
        //模拟一个异步请求，然后回调，得到结果

    }
}



